package com.jiahe.blog.controller.base;

import com.jiahe.blog.common.exception.BlogException;
import com.jiahe.blog.model.StatusConst;
import com.jiahe.blog.model.response.BlogResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return false;
    }


    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return null;
    }


    @ExceptionHandler(BlogException.class)
    public BlogResponse<Void> handler(BlogException e) {
      log.warn(e.getMessage());
      return BlogResponse.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BlogResponse<Void> handler(Exception e) {
        log.error(e.getMessage());
        return BlogResponse.error(StatusConst.SYSTEM_ERROR, e.getMessage());
    }
}
